package service

import (
	"go-ecommerce/internal/model"
	"go-ecommerce/internal/validate"
	"gorm.io/gorm"
)

// CreateOrUpdateMenu 创建或更新菜单
func CreateOrUpdateMenu(db *gorm.DB, menu *model.Menu) error {
	if menu.ID > 0 {
		return db.Model(&model.Menu{}).Where("id = ?", menu.ID).Updates(menu).Error
	}
	return db.Create(menu).Error
}

// GetMenuList 获取所有菜单列表
func GetMenuList(db *gorm.DB) ([]model.Menu, error) {
	var list []model.Menu
	err := db.Order("sort ASC").Find(&list).Error
	return list, err
}

// DeleteMenu 删除菜单
func DeleteMenu(db *gorm.DB, id uint64) error {
	return db.Delete(&model.Menu{}, id).Error
}

// BuildMenuTreeByPermissions 根据权限构建菜单树
func BuildMenuTreeByPermissions(db *gorm.DB, permissionIDs []uint64) ([]validate.MenuTree, error) {
	var allMenus []model.Menu

	// 查询所有菜单
	if err := db.Order("sort ASC").Find(&allMenus).Error; err != nil {
		return nil, err
	}

	// 过滤权限相关菜单（permission_id 为空或在权限列表中）
	menuMap := make(map[uint64][]validate.MenuTree)
	for _, m := range allMenus {
		// 如果菜单权限为空，或在当前权限ID中
		if m.PermissionID == nil || contains(permissionIDs, *m.PermissionID) {
			node := validate.MenuTree{
				ID:    m.ID,
				Title: m.Title,
				Icon:  m.Icon,
				Path:  m.Path,
			}
			menuMap[m.ParentID] = append(menuMap[m.ParentID], node)
		}
	}

	// 递归构建树
	var buildTree func(parentID uint64) []validate.MenuTree
	
	buildTree = func(parentID uint64) []validate.MenuTree {
		children := menuMap[parentID]
		for i := range children {
			children[i].Children = buildTree(children[i].ID)
		}
		return children
	}

	return buildTree(0), nil
}

// contains 检查 permissionID 是否在列表中
func contains(list []uint64, id uint64) bool {
	for _, v := range list {
		if v == id {
			return true
		}
	}
	return false
}
